//
//  BookDetalViewController.m
//  WNZSSQ
//
//  Created by JDKJ on 2018/12/5.
//  Copyright © 2018年 JDKJ. All rights reserved.
//

#import "BookDetalViewController.h"
#import "BookDetailCell.h"
#import "CommentsTableViewCell.h"
#import "CZQCustomNavView.h"
#import "CZQMyMainSharView.h"

@interface BookDetalViewController ()<UITableViewDelegate,UITableViewDataSource>

/**
 //数据源
 */
@property(nonatomic,strong)NSMutableArray *dataArr;


/**
 tableView
 */
@property(nonatomic,weak)UITableView *tableView;

/**
 自定义导航栏
 */
@property(nonatomic,weak)CZQCustomNavView *navView;

/**
 头部cell
 */
@property(nonatomic,weak)BookDetailCell * cell1;

@property(nonatomic,weak)BookDetailCommentView *commentView;

@end

@implementation BookDetalViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"小说详情";
    
    [self creatUI];
    
    /**
     * 监听键盘
     **/
    [NotificationCenter addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [NotificationCenter addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];

}

-(void)creatUI
{
    [self tableView];
    
    CZQCustomNavView *navView = [CZQCustomNavView new];
    self.navView = navView;
    [self.view addSubview:navView];
    [navView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.width.mas_equalTo(self.view);
        make.height.mas_equalTo(adaptNavagationBar);
    }];
    
    navView.popBtn.hidden = NO;
    [navView.rightBtn setImage:@"分享"];
    [navView.rightBtn setTitle:@""];
    navView.titleLable.text = @"斗罗大陆";
    navView.titleLable.hidden = YES;
    navView.bgView.image = PlaceHold2;
    navView.bgView.contentMode = UIViewContentModeTop;
    navView.bgView.clipsToBounds = YES;
    navView.rightBtn.hidden = NO;
    [navView.rightBtn addTarget:self action:@selector(rightBtnClick)];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        
    } else {
        
        self.automaticallyAdjustsScrollViewInsets = YES;
        
    }
    
    BookDetailToolView *toolView = [[BookDetailToolView alloc]init];
    [self.view addSubview:toolView];
    
    [toolView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.left.width.mas_equalTo(self.view);
        make.height.mas_equalTo(adaptTabBar);
        
    }];
    
}



-(void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    
}

#pragma mark - 懒加载

-(NSMutableArray *)dataArr
{
    if (!_dataArr) {
        
        _dataArr = [NSMutableArray array];
        
    }
    
    return _dataArr;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        
        UITableView *tableView=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        
        tableView.delegate=self;
        
        tableView.dataSource=self;
        
        tableView.backgroundColor = [UIColor whiteColor];
        
        tableView.estimatedRowHeight = 150;
        tableView.showsVerticalScrollIndicator = NO;
        [self.view addSubview:tableView];
        
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.width.top.mas_equalTo(self.view);
            make.height.mas_equalTo(SCREENHEIGHT - adaptTabBar);
            
        }];
        
        //        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        
        //注册
        [tableView registerClass:[BookDetailCell class] forCellReuseIdentifier:@"cell1"];
        [tableView registerClass:[CommentsTableViewCell class] forCellReuseIdentifier:@"cell2"];
        [tableView registerClass:[BookDetailSameCell class] forCellReuseIdentifier:@"cell3"];
        [tableView registerClass:[BookDetailChaseCell class] forCellReuseIdentifier:@"cell4"];
        [tableView registerClass:[BookAboutCell class] forCellReuseIdentifier:@"cell5"];
        [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        
        
        
        _tableView = tableView;
    }
    return _tableView;
}

#pragma mark - UITableViewDataSource

//行数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

//列数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1) {
        return self.dataArr.count + 3;
    }
    return  1 ;
}

//cell内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        BookDetailCell * cell1 = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        cell1.selectionStyle = 0;
        self.cell1 = cell1;
        return cell1;
        
    }
    if (indexPath.section == 1) {
        
        CommentsTableViewCell * cell2 = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        cell2.selectionStyle = 0;
        return cell2;
        
    }
    if (indexPath.section == 2) {
        
        BookDetailSameCell * cell3 = [tableView dequeueReusableCellWithIdentifier:@"cell3"];
        cell3.selectionStyle = 0;
        return cell3;
        
    }
    
    if (indexPath.section == 3) {
        
        BookDetailChaseCell * cell4 = [tableView dequeueReusableCellWithIdentifier:@"cell4"];
        cell4.selectionStyle = 0;
        return cell4;
        
    }
    if (indexPath.section == 4) {
        
        BookAboutCell * cell5 = [tableView dequeueReusableCellWithIdentifier:@"cell5"];
        cell5.selectionStyle = 0;
        return cell5;
        
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    return cell;
   
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGFLOAT_MIN;
    }
    return 50;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc]initWithFrame:CGRectZero];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return [[UIView alloc]initWithFrame:CGRectZero];
    }
    
    BookDetailCellHeadView *headView = [[BookDetailCellHeadView alloc]init];
    
    if (section == 1) {
        headView.delBtn.hidden = NO;
        headView.titleLable.text = @"评论";
        [headView.delBtn addTarget:self action:@selector(comment)];
    }else
    {
        headView.delBtn.hidden = YES;
        [headView.delBtn removeTarget:self action:@selector(comment) forControlEvents:UIControlEventTouchUpInside];
        if (section == 2) {
            headView.titleLable.text = @"同类好书";
        }
        if (section == 3) {
            headView.titleLable.text = @"他们都在追";
        }
        if (section == 4) {
            headView.titleLable.text = @"图书相关信息";
        }
    }
    
    return headView;
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //当离开某行时，让某行的选中状态消失
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
}


#pragma mark - UIScrolDelegate
/**
 * 处理联动
 * 因为要实现下拉头部放大的问题，tableView设置了contentInset，所以试图刚加载的时候会调用一遍这个方法，所以要做一些特殊处理，
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //当前偏移量
    CGFloat yOffset  = scrollView.contentOffset.y;
    
    
    
    NSLog(@"%.2f",yOffset);
    
//    CGFloat alpha1 = (adaptNavagationBar + yOffset) /adaptNavagationBar;
    
    
    if (yOffset >  0.1) {
        self.navView.titleLable.hidden = NO;
        self.navView.bgView.hidden = NO;
    }else
    {
        
        self.navView.titleLable.hidden = YES;
        self.navView.bgView.hidden = YES;
        
        self.tableView.contentOffset = CGPointMake(0, 0.1);
    }
}

#pragma mark - 评论

-(void)comment
{
    BookDetailCommentView *commentView = [[BookDetailCommentView alloc]init];
    [commentView addViews];
    self.commentView = commentView;
    [commentView.bottomTF becomeFirstResponder];
    commentView.sureClick  = ^() {
        
        
    };
}


#pragma mark - 分享

-(void)rightBtnClick
{
    WS(weakSelf);
    
    CZQMyMainSharView *shareView = [[CZQMyMainSharView alloc]init];
    [shareView onlyShare];
    [shareView showWithAnimation];
    shareView.shareClick = ^(NSInteger index) {
        
        [weakSelf shareBtnClick:index];
        
    };
    
}


#pragma mark - 分享回调
-(void)shareBtnClick:(NSInteger)index
{
    
    if (index == 0) {
        //微信朋友圈
        
        [self shareToPlatform:UMSocialPlatformType_WechatTimeLine];
        
    }else if (index == 1){
        
        //微信好友
        [self shareToPlatform:UMSocialPlatformType_WechatSession];
        
    }
    else if (index == 2){
        
        //5,//qq空间
        [self shareToPlatform:UMSocialPlatformType_Qzone];
        
    }
    else if (index == 3){
        
        //4,//QQ聊天页面
        [self shareToPlatform:UMSocialPlatformType_QQ];
        
    }
    
}

- (void)shareToPlatform:(UMSocialPlatformType)platformType{
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    
    
    
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"万能追书" descr:@"" thumImage:PlaceHold];
    
    //设置网页地址
    shareObject.webpageUrl = @"htps://www.baidu.com";
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    /**
     设置分享
     
     @param data 分享返回信息
     @param error 失败信息
     @param UMSocialPlatformType 分享平台
     */
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            //错误码
            
            NSString *result;
            switch (error.code) {
                case UMSocialPlatformErrorType_Unknow:
                    result = @"未知错误";
                    break;
                case UMSocialPlatformErrorType_NotSupport:
                    result = @"不支持（url scheme 没配置，或者没有配置-ObjC， 或则SDK版本不支持或则客户端版本不支持";
                    break;
                case UMSocialPlatformErrorType_AuthorizeFailed:
                    result = @"授权失败";
                    break;
                case UMSocialPlatformErrorType_ShareFailed:
                    result = @"分享失败";
                    break;
                case UMSocialPlatformErrorType_RequestForUserProfileFailed:
                    result = @"请求用户信息失败";
                    break;
                case UMSocialPlatformErrorType_ShareDataNil:
                    result = @"分享内容为空";
                    break;
                case UMSocialPlatformErrorType_ShareDataTypeIllegal:
                    result = @"分享内容不支持";
                    break;
                case UMSocialPlatformErrorType_CheckUrlSchemaFail:
                    result = @"schemaurl fail";
                    break;
                case UMSocialPlatformErrorType_NotInstall:
                    result = @"应用未安装";
                    break;
                case UMSocialPlatformErrorType_Cancel:
                    result = @"您已取消分享";
                    break;
                case UMSocialPlatformErrorType_NotNetWork:
                    result = @"网络异常";
                    break;
                case UMSocialPlatformErrorType_SourceError:
                    result = @"第三方错误";
                    break;
                case UMSocialPlatformErrorType_ProtocolNotOverride:
                    result = @"对应的    UMSocialPlatformProvider的方法没有实现";
                    break;
                default:
                    break;
            }
            
            [MBProgressHUD showText:result];
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
    
}

#pragma mark - 键盘处理
- (void)keyBoardWillShow:(NSNotification *)notice
{
    
    // 取出键盘高度
    CGRect keyboardF = [notice.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyBoardHeight = keyboardF.size.height;
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[notice.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    
    [self.commentView.whiteView mas_remakeConstraints:^(MASConstraintMaker *make) {
        
        make.left.width.mas_equalTo(self.commentView);
        make.bottom.mas_equalTo(self.commentView).offset(-keyBoardHeight + 10);
    }];
    
    
    
    
    
}

-(void)keyBoardWillHide:(NSNotification *)notice
{
    
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[notice.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    
    CGFloat height = self.commentView.whiteView.frame.size.height;
    [UIView animateWithDuration:duration animations:^{
        self.commentView.whiteView.center = CGPointMake(SCREEN_WIDTH / 2, SCREEN_HEIGHT + height / 2);
        self.commentView.alphaView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.0];
    } completion:^(BOOL finished) {
        [self.commentView  removeFromSuperview];
    }];
    
    

}



#pragma mark 退出键盘
-(void)tapClick{
    
    [self.view endEditing:YES];
}


- (void)dealloc {
    
    
    
    [NotificationCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [NotificationCenter removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [NotificationCenter removeObserver:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
